package DAO;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import obj.Categorie;
import DAO.DAO;

public class CategorieDAO extends DAO<Categorie> {

	public Categorie create(Categorie obj) {
		try {
			PreparedStatement ps = this.connect
					.prepareStatement("INSERT INTO TYPE(T_LIB) VALUES('"+obj.getLib()+"')");
			ps.executeUpdate();
			ps.close();
			obj = this.find(obj.getLib());
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return obj;
	}

	public Categorie find(String id) {
		Categorie categ = new Categorie();
		try {
			ResultSet rs = this.connect.createStatement(
					ResultSet.TYPE_SCROLL_INSENSITIVE,
					ResultSet.CONCUR_UPDATABLE).executeQuery(
					"SELECT * FROM CATEGORIE WHERE C_LIB='" + id+"'");
			if (rs.first()) {
				categ = new Categorie(id);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return categ;
	}

	public Categorie update(Categorie obj) {
		try {
			PreparedStatement ps = this.connect
					.prepareStatement("UPDATE CATEGORIE SET C_LIB='"+obj.getLib()+"' WHERE C_LIB ='"+obj.getLib()+"'");
			ps.executeUpdate();
			ps.close();
			obj = this.find(obj.getLib());
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return obj;
	}

	public void delete(Categorie obj) {
		try {
			PreparedStatement ps = this.connect
					.prepareStatement("DELETE FROM CATEGORIE WHERE C_LIB ='"+obj.getLib()+"'");
			ps.executeUpdate();
			ps.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public ArrayList<String> selectAll() {
		ArrayList<String> ltype= new ArrayList<String>();
		try {
			ResultSet rs = this.connect.createStatement(
					ResultSet.TYPE_SCROLL_INSENSITIVE,
					ResultSet.CONCUR_UPDATABLE).executeQuery(
					"SELECT * FROM CATEGORIE");
			
			while(rs.next()){
				ltype.add(rs.getString(1));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return ltype;
	}
}
